package perdev.skiloop.accelerometerflashlight;

import android.content.Context;
import android.hardware.*;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity implements SensorEventListener {
    private SensorManager mSensorManager;
    private boolean m_IsOn = false;
    private Camera mCamera;
    private Camera.Parameters mParameters;
    private Button mButton;
    private double mGValue = 9.8;
    private double mDelta = 0.4;
    private long mSleepTime = 5000;
    private TextView mStatusTextView;

    private boolean isOn() {
        return m_IsOn;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new DummyFragment())
                    .commit();
        }
        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);

        mButton = (Button) findViewById(R.id.flash_light_control_button);
        mStatusTextView = (TextView) findViewById(R.id.status_text_view);
        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changeFlashLightState();
            }
        });

    }



    private void turnOnFlashLight() {
        try {
            mCamera = Camera.open();
            mParameters = mCamera.getParameters();
            mParameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
            mCamera.setParameters(mParameters);
            m_IsOn = true;
            mStatusTextView.setText(getResources().getString(R.string.flash_light_on));
            mButton.setText(R.string.turn_off);
        } catch (Exception ex) {

        }

    }

    private void turnOffFlashLight() {
        try {
            mParameters = mCamera.getParameters();
            mParameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
            mCamera.setParameters(mParameters);
            mCamera.release();
            m_IsOn = false;
            mStatusTextView.setText(getResources().getString(R.string.flash_light_off));
            mButton.setText(R.string.turn_on);
        } catch (Exception ex) {

        }

    }

    private void changeFlashLightState() {
        if (isOn()) {
            turnOffFlashLight();
        } else {
            turnOnFlashLight();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        switch (item.getItemId()) {
            case R.id.action_settings:
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
                SensorManager.SENSOR_DELAY_NORMAL);
    }

    @Override
    protected void onStop() {
        mSensorManager.unregisterListener(this);
        super.onStop();
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
            float values[] = event.values;
            double g = Math.sqrt(values[0] * values[0] + values[1] * values[1] + values[2] * values[2]);
            if (Math.abs(mGValue - g) > mDelta) {
                changeFlashLightState();
                threadSleepIfOn();
            }
            mGValue = g;
        }
    }

    private void threadSleepIfOn() {
        if (isOn()) {
            try {
                Thread.sleep(mSleepTime);
            } catch (InterruptedException e) {

            }
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

    /**
     * A dummy fragment containing a simple view.
     */
    public static class DummyFragment extends Fragment {

        public DummyFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container, false);
            return rootView;
        }
    }

}
